package com.atguigu.daijia.driver.service.impl;

import com.atguigu.daijia.common.execption.GuiguException;
import com.atguigu.daijia.common.result.Result;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import com.atguigu.daijia.driver.client.CosFeignClient;
import com.atguigu.daijia.driver.config.MinioProperties;
import com.atguigu.daijia.driver.service.FileService;
import com.atguigu.daijia.model.vo.driver.CosUploadVo;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class FileServiceImpl implements FileService {

	@Autowired
	private CosFeignClient cosFeignClient;

	@Autowired
	private MinioProperties minioProperties;

	// 文件上传接口
	@Override
	public CosUploadVo uploadFile(MultipartFile file, String path) {
		// 远程调用文件存储服务，实现文件上传
		Result<CosUploadVo> cosUploadVoResult = cosFeignClient.upload(file, path);
		// 提取并返回上传结果数据
		CosUploadVo cosUploadVo = cosUploadVoResult.getData();
		return cosUploadVo;
	}

	@Override
	public String upload(MultipartFile file) {
		try {
			// 创建一个Minio的客户端对象
			MinioClient minioClient = MinioClient.builder()
					.endpoint(minioProperties.getEndpointUrl())
					.credentials(minioProperties.getAccessKey(), minioProperties.getSecreKey())
					.build();

			// 判断桶是否存在
			boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
			if (!found) {       // 如果不存在，那么此时就创建一个新的桶
				minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
			} else {  // 如果存在打印信息
				System.out.println("Bucket 'daijia' already exists.");
			}

			// 设置存储对象名称
			String extFileName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
			String fileName = new SimpleDateFormat("yyyyMMdd")
					.format(new Date()) + "/" + UUID.randomUUID().toString().replace("-" , "") + "." + extFileName;

			PutObjectArgs putObjectArgs = PutObjectArgs.builder()
					.bucket(minioProperties.getBucketName())
					.stream(file.getInputStream(), file.getSize(), -1)
					.object(fileName)
					.build();
			minioClient.putObject(putObjectArgs) ;

			return minioProperties.getEndpointUrl() + "/" + minioProperties.getBucketName() + "/" + fileName ;

		} catch (Exception e) {
			throw new GuiguException(ResultCodeEnum.DATA_ERROR);
		}
	}
}
